package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Answer;
import com.itheima.mapper.AnswerMapper;
import com.itheima.service.AnswerService;
import com.itheima.entity.UResult;
import com.itheima.mapper.ResultMapper;
import com.itheima.vo.answerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户角色关系表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2021-04-04
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, Answer> implements AnswerService {
    @Autowired
    AnswerMapper answerMapper;
    @Autowired
    ResultMapper resultMapper;

    @Override
    public void insertOrUpdate(Answer answer) {
        // 0 创建条件
        LambdaQueryWrapper<Answer> Wrapper = new LambdaQueryWrapper<>();
        Wrapper.eq(Answer::getUserId, answer.getUserId());
        // 1 看看有没有插入过
        List<Answer> answerList = answerMapper.selectList(Wrapper);
        // 如果有记录，就update
        if (answerList.size() > 0) answerMapper.update(answer, Wrapper);
            // 不然的话就insert
        else answerMapper.insert(answer);
    }

    @Override
    public void creatResult(answerVo answerVo) {
        int score = 0;
        // 如果做完（不判断result有没有做过，也不判断answer的IsSubmit，因为能进到这说明没有做过，以及做完了）
        // 拿已选选项
        List<Integer> answerList = answerVo.getAnswer();
        for (Integer integer : answerList) {
            // 全部加到总分里面去
            score += ++integer;
        }
        // new一个result
        UResult UResult = new UResult();
        // 填满result
        UResult.setScore(score);
        UResult.setCourseId(answerVo.getCourseId());
        UResult.setCoursename(answerVo.getCourseName());
        UResult.setUserId(answerVo.getUserId());
        // 插入结果
        resultMapper.insert(UResult);
    }
}
